package com.fishingwithme.android.ui.screens.map

// Import missing classes
import android.util.Log
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.fishingwithme.android.data.model.Position
import com.fishingwithme.android.ui.screens.map.handlers.MapEventHandler
import com.tencent.tencentmap.mapsdk.maps.TencentMap
import com.tencent.tencentmap.mapsdk.maps.TencentMap.MAP_TYPE_NORMAL
import com.tencent.tencentmap.mapsdk.maps.TencentMapInitializer
import com.tencent.tencentmap.mapsdk.maps.TextureMapView


@Composable
fun TencentMapWrapper(
    modifier: Modifier = Modifier,
    permissionsGranted: Boolean,
    moduleKey: String,
    data: MutableMap<String, Any>,
    onNavigateBack: ((String) -> Unit)? = null,
    onMapCameraChanged: ((Position) -> Unit)? = null,
    changeKey: String = "" // Add changeKey parameter
) {
    // 创建侧边栏菜单项
    val barItems by remember { mutableStateOf(mutableListOf<SideBarItem>()) }

    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current

    // Keep track of the last processed data hash to avoid unnecessary refreshes
    val lastDataHash = remember { mutableStateOf<Int?>(null) }
    val currentData by rememberUpdatedState(data)

    // 关键修复：在remember中创建TextureMapView，确保实例不会频繁重建
    TencentMapInitializer.setAgreePrivacy(context, true)
    TencentMapInitializer.start(context);
    val mapView = remember {
        TextureMapView(context).apply {
            // 初始化地图参数
            layoutParams = android.view.ViewGroup.LayoutParams(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
    }

    // Create MapOperationContext and populate with initial data
    // Create MapOperationContext empty
    val mapContext = remember {
        MapOperationContext()
    }

    val controller = remember {
        DefaultMapWrapperController(context, mapContext).apply {
            // Set the navigation callback
            this.onNavigateBack = onNavigateBack
        }
    }

    // 修复1：正确管理TextureMapView的生命周期
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->

            when (event) {
                Lifecycle.Event.ON_START -> mapView.onStart()
                Lifecycle.Event.ON_RESUME -> mapView.onResume()
                Lifecycle.Event.ON_PAUSE -> mapView.onPause()
                Lifecycle.Event.ON_STOP -> mapView.onStop()
                Lifecycle.Event.ON_DESTROY -> {
                    // Remove all markers and listeners before destroying the map
                    try {
                        controller.fullCleanup()
                    } catch (e: Exception) {
                        Log.w("TencentMapWrapper", "Error during controller cleanup", e)
                    }
                    mapView.onDestroy()
                }

                else -> {}
            }
        }

        val lifecycle = lifecycleOwner.lifecycle
        lifecycle.addObserver(observer)

        onDispose {
            lifecycle.removeObserver(observer)
        }
    }

    // 修复2：延迟初始化地图配置，确保视图已准备好
    DisposableEffect(mapView) {
        val tencentMap = mapView.map
        if (tencentMap != null) {
            setupMap(tencentMap, permissionsGranted, onMapCameraChanged)
            barItems.addAll(controller.init(moduleKey, tencentMap))
        }
        onDispose {
            // Cleanup logic if needed
        }
    }

    // Monitor only the changeKey parameter for refresh triggers
    DisposableEffect(mapView, changeKey) {
        try {
            // Only refresh if map is initialized and not destroyed
            val tencentMap = mapView.map
            if (tencentMap != null) {
                // Calculate hash of current data to determine if it has actually changed
                val currentHash = currentData.hashCode()
                val previousHash = lastDataHash.value

                // Only refresh if data has actually changed
                if (previousHash == null || previousHash != currentHash) {
                    mapContext.data.clear()
                    currentData.forEach { (key, value) ->
                        mapContext.data[key] = value
                    }
                    // Call controller refresh when changeKey changes
                    controller.doMapRefresh()
                    // Update the last processed hash
                    lastDataHash.value = currentHash
                }
            } else {
                Log.w("TencentMapWrapper", "Map not initialized or destroyed, skipping refresh")
            }
        } catch (e: Exception) {
            Log.e("TencentMapWrapper", "Error calling doMapRefresh", e)
        }

        onDispose {
            // Cleanup logic if needed
            Log.d("TencentMapWrapper", "DisposableEffect disposed")
        }
    }

    // 修复3：使用AndroidView包装TextureMapView
    androidx.compose.ui.viewinterop.AndroidView(
        factory = { mapView },
        modifier = modifier.fillMaxSize()
    )

    // 添加地图侧边栏菜单
    SideBar(
        barItems = barItems,
        onItemClick = { handler ->
            controller.setActiveHandler(handler as MapEventHandler)
        }
    )
}

/**
 * 配置地图基础属性和行为
 */
private fun setupMap(
    tencentMap: TencentMap,
    permissionsGranted: Boolean,
    callback: ((Position) -> Unit)? = null
) {
    tencentMap.mapType = MAP_TYPE_NORMAL
    // 启用基本交互
    with(tencentMap.uiSettings) {
        isZoomGesturesEnabled = true
        isScrollGesturesEnabled = true
        isTiltGesturesEnabled = true
        isRotateGesturesEnabled = true
        isRotateGesturesEnabled = true
        // 根据权限设置是否启用我的位置图层
        //isMyLocationButtonEnabled = permissionsGranted
    }
    // 根据权限设置是否启用我的位置图层
    tencentMap.isMyLocationEnabled = permissionsGranted

    // Implement camera change listener
    val listener = object : TencentMap.OnCameraChangeListener {
        override fun onCameraChange(cameraPosition: com.tencent.tencentmap.mapsdk.maps.model.CameraPosition?) {
            // Handle camera change if needed
            // Log.d("TencentMapWrapper", "Camera changed: ${cameraPosition?.target}")
        }

        override fun onCameraChangeFinished(cameraPosition: com.tencent.tencentmap.mapsdk.maps.model.CameraPosition?) {
            // Handle camera change finished event
            Log.d("TencentMapWrapper", "Camera change finished: ${cameraPosition?.target}")
            // Notify ViewModel about camera changes
            if (cameraPosition != null && cameraPosition.target != null) {
                callback?.invoke(
                    Position(
                        cameraPosition.target.latitude,
                        cameraPosition.target.longitude
                    )
                )
            }
        }
    }

    tencentMap.setOnCameraChangeListener(listener)
}